package com.oracle.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oracle.bean.LoginUser;
import com.oracle.entity.Oauser;
import com.oracle.mapper.OauserMapper;
import com.oracle.service.OauserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oracle.util.JJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2025年05月15日
 */
@Service
public class OauserServiceImpl extends ServiceImpl<OauserMapper, Oauser> implements OauserService {

    @Autowired
    private OauserMapper oauserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Oauser findUserById(Integer id) {
        return oauserMapper.selectById(id);
    }

    @Override
    public Map<String, String> login(Oauser user) {

        //通过UsernamePasswordAuthenticationToken获取用户名和密码 是用户填写的用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getLoginname(),user.getPassword());

        //AuthenticationManager委托机制对authenticationToken 进行用户认证
        //authenticate 调用 UserDetailsServiceImpl 的 loadUserByUsername
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没有通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //如果认证通过，使用user生成jwt  jwt存入ResponseResult 返回

        //如果认证通过，拿到这个当前登录用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        //获取当前用户的userid
        //脱敏
        loginUser.getOauser().setPassword(null);

        String jsonString = JSON.toJSONString(loginUser.getOauser());
        String jwt = JJwtUtil.createJWT(jsonString);
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        map.put("id",loginUser.getOauser().getId()+"");
        map.put("truename",loginUser.getOauser().getTruename());
        map.put("loginname",loginUser.getOauser().getLoginname());

        //把完整的用户信息存入redis  userid为key   用户信息为value
        stringRedisTemplate.opsForValue().set("login:"+loginUser.getOauser().getLoginname(),
                JSON.toJSONString(loginUser.getOauser()),2, TimeUnit.HOURS);


        return map;
    }

    @Override
    public void register(Oauser oauser) {
        //将 明文密码 进行加密 变成密文
        String pwd = passwordEncoder.encode(oauser.getPassword());
        System.out.println("pwd : " + pwd);
        oauser.setPassword(pwd);
        oauserMapper.insert(oauser);
    }

    @Override
    public Oauser findUserByMobile(String mobile) {

        QueryWrapper<Oauser> wrapper = new QueryWrapper<Oauser>();
        wrapper.eq("phone",mobile);
        return oauserMapper.selectOne(wrapper);

    }
}
